package com.community.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.community.common.mapper.*;
import com.community.common.pojo.Constant;
import com.community.common.pojo.constant.CameraSnConstant;
import com.community.common.pojo.domain.*;
import com.community.common.pojo.forcamera.entity.CameraPersonAdd;
import com.community.common.pojo.forcamera.response.CameraPersonAddResVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 相机请求服务实现类
 * Created by Enzo Cotter on 2020/9/18.
 */
@Slf4j
@Service
public class ForCameraService {

    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private OwnerFriendMapper ownerFriendMapper;
    @Resource
    private PublicUserMapper publicUserMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private CameraMapper cameraMapper;

    private final FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public List<CameraPersonAdd> getCameraPersonAdd(String sn) {
        List<CameraPersonAdd> resultList = new LinkedList<>();
        //查出当前相机所在的小区
        LambdaQueryWrapper<Camera> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Camera::getSn, sn);
        Camera camera = cameraMapper.selectOne(wrapper);
        if (camera == null) {
//            log.info("当前相机SN：{} 未查询到", sn);
            return null;
        }
        //更新心跳时间
        camera.setHeartTime(LocalDateTime.now());
        cameraMapper.updateById(camera);

        String communityId = camera.getCommunityId();
        //查询出10条需要返回给相机的数据 (当前权限状态 != 目标权限状态）
        List<UserPermission> records = userPermissionMapper.selectToSend(communityId, camera.getId());
        records.forEach(record -> {
            CameraPersonAdd.CameraPersonAddBuilder personAddBuilder = CameraPersonAdd.builder();
            personAddBuilder.id(record.getId());
            if (record.getTargetAllow() == 1) {
                personAddBuilder = personAdd(personAddBuilder, record);
            } else {
                personDel(personAddBuilder);
            }
            //将命令状态更新为 执行中
            record.setCommandStatus(Constant.COMMAND_ONGOING);
            userPermissionMapper.updateById(record);
            if (personAddBuilder != null) {
                resultList.add(personAddBuilder.build());
            }
        });
        return resultList;
    }


    public void cmdCallback(CameraPersonAddResVo cameraPersonAddResVo) {
        Boolean success = cameraPersonAddResVo.getSuccess();
        String sn = cameraPersonAddResVo.getSn();
        List<CameraPersonAdd> data = cameraPersonAddResVo.getData();
        if (!CollectionUtils.isEmpty(data)) {
            for (CameraPersonAdd datum : data) {
                StringBuilder sb = new StringBuilder();
                sb.append("=========> 添加到相机回调 \n success:{} \n sn:{} \n ID：{} \n 姓名：{} \n ");
                UserPermission userPermission = userPermissionMapper.selectById(datum.getId());
                if (userPermission == null) {
                    sb.append(" ID在数据库中找不到 ");
                } else {
                    userPermission.setCurrentAllow(success ? userPermission.getTargetAllow() : userPermission.getCurrentAllow());
                    userPermission.setCommandStatus(success ? Constant.COMMAND_SUCCESS : Constant.COMMAND_FAIL);
                    userPermission.setUpdateTime(LocalDateTime.now());
                    userPermissionMapper.updateById(userPermission);
                    sb.append(" 更新数据库成功 ");
                }
                log.info(sb.toString(), success, sn, datum.getId(), datum.getName());
            }
        }
    }

    public CameraPersonAdd.CameraPersonAddBuilder personAdd(CameraPersonAdd.CameraPersonAddBuilder personAddBuilder, UserPermission record) {
        String relevanceId = record.getRelevanceId();
        personAddBuilder
                .cmd("add")
                .passPeriod("00:00~23:59")
                .startTime(df.format(record.getStartTime()))
                .expireTime(df.format(record.getEndTime()));
        if (record.getIdTable() == 0) {
            LambdaQueryWrapper<PublicUser> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(PublicUser::getId, relevanceId);
            PublicUser publicUser = publicUserMapper.selectOne(wrapper1);
            personAddBuilder.name(publicUser.getName())
                    .idCard(publicUser.getIdCard());
            // 处理照片信息
            Picture picture = pictureMapper.selectById(publicUser.getPictureId());
            if (picture != null) {
                personAddBuilder.facePicture(picture.getUrl());
            } else {
                log.warn("当前用户 publicUser id：{} name：{} 没有照片信息 ", publicUser.getId(), publicUser.getName());
            }
        } else {
            LambdaQueryWrapper<OwnerFriend> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(OwnerFriend::getId, relevanceId);
            OwnerFriend ownerFriend = ownerFriendMapper.selectOne(wrapper2);
            if (ownerFriend == null) {
                log.warn("id：{} 的 可能已经删除 删除此条userPermission记录 ", relevanceId);
                userPermissionMapper.deleteById(record);
                personAddBuilder = null;
            } else {
                personAddBuilder.name(ownerFriend.getName())
                        .idCard(ownerFriend.getIdCard());
                // 处理照片信息
                Picture picture = pictureMapper.selectById(ownerFriend.getPictureId());
                if (picture != null) {
                    personAddBuilder.facePicture(picture.getUrl());
                } else {
                    log.warn("当前用户 ownerFriend id：{} name：{} 没有照片信息 ", ownerFriend.getId(), ownerFriend.getName());
                }
            }
        }
        return personAddBuilder;
    }

    public void personDel(CameraPersonAdd.CameraPersonAddBuilder personAddBuilder) {
        personAddBuilder
                .cmd("delete")
                .deleteRecord(true);
    }

}
